/**
 * 测试Writable的序列化
 * 引入ByteArrayOutputStream，包装流
 * 先写入序列化，在读取反序列化
 */
package com.tjh.hadoop.writable;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.junit.Test;

/**
 * @author jahen
 * @date 2016年9月11日
 * @time 下午12:49:35
 * @category Hadoop 
 */
public class TestSerialize {
	
	
	/**
	 *序列化, 将对象写入字节流中
	 */
	public byte[]  serialize(Writable writable) throws Exception{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(out);
		
		writable.write(dos);
		dos.close();
		
		return out.toByteArray();
	}
	
	/**
	 * 反序列化，从字节流中读出读出数据
	 */
	public byte[] deSerialize(Writable writable, byte[] bytes) throws Exception{
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		DataInputStream bis = new DataInputStream(in);
		
		writable.readFields(bis);
		bis.close();
		
		return bytes;
	}
	
	@Test
	public void test() throws Exception{
		IntWritable value = new IntWritable();
		value.set(163);
		// 序列化
		byte[] bytes = serialize(value);
		// 判断 写入的是一个整型值
		assertThat(bytes.length, is(4));
		
		IntWritable value2 = new IntWritable();
		// 反序列化
		deSerialize(value2, bytes);
		// 判断  读出的结果
		assertThat(value2.get(), is(163));
	}
}
